// @ts-nocheck
import device from '@system.device';
import router from '@system.router';
import app from '@system.app';
import config from '../../../../js/share/common/config/config.js'
import bleOperator from '../../../../js/share/common/opinterface/bleoperator.js'
import commonOperator from '../../../../js/share/common/opinterface/commonoperator.js'
import bleDataUtils from '../../../../js/share/common/util/bleDataUtils.js'
import Log from '../../../share/common/util/log.js'
import permissionHelper from '../../../share/common/util/permissionHelper.js'
import {showToast} from '../../../share/common/util/util.js'

const TAG = 'index';
var context;

//var getDeviceInfo = function () {
//    var res = '';
//    device.getInfo({
//        success: function (data) {
//            console.log(TAG + 'Success device obtained. screenShape=' + data.screenShape);
//            this.res = data.screenShape;
//        },
//        fail: function (data, code) {
//            console.log(TAG + 'Failed to obtain device. Error code=' + code + '; Error information: ' + data);
//        },
//    });
//    return res;
//};
export default {
    data: {
        initial_value: 0,
        macAddr: '11:22:88:44:55:66',
        //        macAddr: '11:22:88:44:55:67',
        deviceName: "Name",
        deviceState: 0, //0 未连接   1  连接中   2已连接   3连接断开
        deviceStateInfo: {
            startConnect: "开始连接", // 0
            connecting: "正在连接...", //1
            disconnect: "断开连接", //2
            reconnect: "重新连接", //3
        },
        colorHex: '',
        showPopup: false,
        tagId: '',
        reportValue1: '0',
        reportValue2: '0',
        reportValue3: '0',
        threshold1: '0',
        threshold2: '0',
        threshold3: '0',
    },
    onInit() {
        Log.log(TAG + 'onInit');
        this.context = this;
        if (this.params == undefined) {
            Log.error('Params is undefined!');
        } else {
            let paramJson = JSON.parse(this.params);
            Log.info('Params init success:' + JSON.stringify(paramJson));
            this.macAddr = paramJson.macAddr;
            this.$app.$def.globalData.macAddr = paramJson.macAddr;
        }
        this.checkAndRequestPermissions();
    },
    onReady() {
        Log.log(TAG + 'onReady');

    },
    onShow() {
        Log.log(TAG + 'onShow');
    },
    initListener() {
        bleOperator.onBleConnectionStateChange(this.onBleConnectionStateChange);
        bleOperator.onBluetoothAdapterStateChange(this.onBluetoothAdapterStateChange);
        bleOperator.onBleCharacteristicValueChange(this.onBleCharacteristicValueChange);
    },
    onBleConnectionStateChange(callbackJson) {
        //dealing with connection state change
        Log.info("onBleConnectionStateChange" + 'Connection state changed: ' + JSON.stringify(callbackJson));
        if (callbackJson.data.isConnected) {
            this.macAddr = callbackJson.data.deviceId
            clearTimeout(this.connectTimeout);
            this.onDeviceConnected()
        } else {
            if (this.deviceState == 2) {
                showToast("设备已断开连接，请重新连接!")
            }
            this.deviceState = 3
            this.tagId = ''
        }
    },
    onBluetoothAdapterStateChange(callbackJson) {
        Log.info('Adapter state changed:' + JSON.stringify(callbackJson));
        if (callbackJson.data.isAvailable == false) {
            this.deviceState = 3;
            this.tagId = ''
            clearTimeout(this.connectTimeout);
        } else {
            this.onAdapterAvailable()
        }
    },
    onBleCharacteristicValueChange(callbackJson) {
        Log.info("onBleCharacteristicValueChange" + ' value changed: ' + JSON.stringify(callbackJson));
        switch (callbackJson.data.characteristicId) {
            case config.CharacterNotify_UUID:
                this.dataTreating(callbackJson.data.changeData.toUpperCase());

                break;
            default:
                break;
        }
    },
    dataTreating(changeData) {
        if (!bleDataUtils.verifyProtocol(changeData)) {
            showToast("设备上报数据校验失败!")
            return;
        }
        let tagDataArray = bleDataUtils.parseCharacteristic(changeData)
        Log.info("dataTreating" + ' tagDataArray: ' + JSON.stringify(tagDataArray));
        this.initViewByTag(tagDataArray)
        tagDataArray.forEach(element => {
            let tag = element[0]
            let value = parseInt(element[2], 16)
            switch (this.tagId) {
                case '00070009': //双传感器组合
                    if (tag == '0007') {
                        this.reportValue1 = value
                    } else if (tag == '0008') {
                        this.threshold1 = value
                    } else if (tag == '0009') {
                        this.reportValue2 = value
                    } else if (tag == '000A') {
                        this.reportValue3 = value
                    } else if (tag == '000B') {
                        this.threshold2 = value
                    } else if (tag == '000C') {
                        this.threshold3 = value
                    }
                    break;
                case '0001':
                    if (tag == '0001') {
                        this.reportValue1 = value
                    }
                    break;
                case '0003':
                    if (tag == '0003') {
                        this.reportValue1 = value
                    } else if (tag == '0004') {
                        this.reportValue2 = value
                    } else if (tag == '0005') {
                        this.reportValue3 = value
                    }
                    break;
                case '0007':
                    if (tag == '0007') {
                        this.reportValue1 = value
                    } else if (tag == '0008') {
                        this.threshold1 = value
                    }
                    break;
                case '0009':
                    if (tag == '0009') {
                        this.reportValue1 = value
                    } else if (tag == '000A') {
                        this.reportValue2 = value
                    } else if (tag == '000B') {
                        this.threshold1 = value
                    } else if (tag == '000C') {
                        this.threshold2 = value
                    }
                    break;
                case '000D':
                    if (tag == '000D') {
                        this.reportValue1 = value / 10.0
                    } else if (tag == '000E') {
                        this.threshold1 = value / 10.0
                    }
                    break;
                case '000F':
                    if (tag == '000F') {
                        this.reportValue1 = value
                    } else if (tag == '0010') {
                        this.reportValue2 = value
                    } else if (tag == '0011') {
                        this.reportValue3 = value
                    }
                    break;
                case '0012':
                    if (tag == '0012') {
                        this.reportValue1 = value
                    } else if (tag == '0019') {
                        this.reportValue2 = value
                    }
                    break;
                case '0013':
                    if (tag == '0013') {
                        this.reportValue1 = value
                    } else if (tag == '001A') {
                        this.reportValue2 = value
                    } else if (tag == '001B') {
                        this.reportValue3 = value
                    } else if (tag == '0014') {
                        this.threshold1 = value
                    }
                    this.colorHex = "#"
                    + parseInt(this.reportValue1).toString(16).padStart(2, "0")
                    + parseInt(this.reportValue2).toString(16).padStart(2, "0")
                    + parseInt(this.reportValue3).toString(16).padStart(2, "0")
                    break;
                case '0015':
                    if (tag == '0015') {
                        this.reportValue1 = value
                    }
                    break;
                case '0016':
                    if (tag == '0016') {
                        this.reportValue1 = value / 10000.0
                    } else if (tag == '0017') {
                        this.reportValue2 = value / 10000.0
                    } else if (tag == '0018') {
                        this.reportValue3 = value
                    }
                    break;
                case '001A':
                    if (tag == '001A') {
                        this.reportValue1 = value
                    } else if (tag == '001B') {
                        this.reportValue2 = value
                    }
                    break;
                case '001C':
                    if (tag == '001C') {
                        this.reportValue1 = value
                        this.threshold1 = value
                    }
                    break;
                case '001D':
                    if (tag == '001D') {
                        this.reportValue1 = value
                    } else if (tag == '001E') {
                        this.reportValue2 = value
                    }
                    break;
                default:
                    break;
            }
        });

    },
    initViewByTag(tagDataArray) {
        let tagIds = new Array()
        for (var i = 0; i < tagDataArray.length; i++) {
            let element = tagDataArray[i]
            tagIds[i] = element[0]
        }
        if (tagIds.includes('0007') && tagIds.includes('0009')) {
            this.tagId = "00070009"
            this.deviceName = "智慧农业感应板"
        } else if (tagIds.includes('0001')) {
            this.tagId = "0001"
            this.deviceName = "火焰感应板"
        } else if (tagIds.includes('0003')) {
            this.tagId = "0003"
            this.deviceName = "可燃气体感应板"
        } else if (tagIds.includes('0007')) {
            this.tagId = "0007"
            this.deviceName = "土壤湿度传感器"
        } else if (tagIds.includes('0009')) {
            this.tagId = "0009"
            this.deviceName = "环境温湿度"
        } else if (tagIds.includes('000D')) {
            this.tagId = "000D"
            this.deviceName = "酒精乙醇感应板"
        } else if (tagIds.includes('000F')) {
            this.tagId = "000F"
            this.deviceName = "颜色传感器"
        } else if (tagIds.includes('0012')) {
            this.tagId = "0012"
            this.deviceName = "心率血氧感应板"
        } else if (tagIds.includes('0013')) {
            this.tagId = "0013"
            this.deviceName = "空气质量监测板"
        } else if (tagIds.includes('0015')) {
            this.tagId = "0015"
            this.deviceName = "红外测温感应板"
        } else if (tagIds.includes('0016')) {
            this.tagId = "0016"
            this.deviceName = "高度与北斗定位感应板"
        } else if (tagIds.includes('001C')) {
            this.tagId = "001C"
            this.deviceName = "照明功能板"
        } else if (tagIds.includes('001D')) {
            this.tagId = "001D"
            this.deviceName = "人体感应功能板"
        }
        Log.info("dataTreating" + ' tagIds: ' + JSON.stringify(tagIds) + ' tagId: ' + this.tagId);
    },
    async onDeviceConnected() {
        this.deviceState = 2
        this.showPopup = false
        bleOperator.notifyBleCharacteristicValueChange(this.macAddr, config.Service_UUID, config.CharacterNotify_UUID, true);
        await this.getDeviceInfo()
    },
    //APP请求设备状态功能,MCU收到此条指令后上报设备当前状态
    getDeviceInfo() {
        var This = this
        var command = bleDataUtils.getTagsCommandHexStr("0001", config.MType[1], 0)
        setTimeout(() => {
            This.writeBleData(command)
        }, 200)
    },
    //下发测量数据
    writeBleData(data) {
        Log.info("writeBleData value = " + data);
        bleOperator.writeBleCharacteristicValue(this.macAddr, config.Service_UUID, config.CharacterWrite_UUID, data, callbackJson => {
            Log.info("writeBleCharacteristicValue value" + JSON.stringify(callbackJson));

        })

    },
    checkAndRequestPermissions() {
        if (config.scanRequired) {
            Log.debug(TAG + 'Location permission is required for scanning, start checking and requiring...');
            permissionHelper.checkAndRequestPermission()
                .then(this.onPermissionGranted)
                .catch(this.onPermissionDenied);
        } else {
            this.onPermissionGranted()
        }
    },
    onPermissionGranted() {
        // Permission is granted for next step, Bluetooth adapter state is
        // checked for next step.
        Log.debug(TAG + "permission Granted!");
        this.initListener();
        this.checkAdapterState();
    },
    onPermissionDenied(data) {
        Log.error(TAG + "permission Denied! permissionForbidden=" + data.permissionForbidden);
        if (data.permissionForbidden) {
            showToast(this.$t('strings.public_permission_forbidden_hint_title', {
                appName: this.$t('strings.custom_name')
            }))
        }
    },
    async checkAdapterState() {
        if (await this.isBleOpen()) {
            this.onAdapterAvailable();
        } else {
            bleOperator.openBluetoothAdapter();
        }
    },
    async onAdapterAvailable() {

        Log.info('onAdapterAvailable scanRequired=' + config.scanRequired)
        this.scanDevice();
    },
    scanDevice() {
        this.deviceState = 1
        this.showPopup = true
        this.connectTimeout = setTimeout(() => {
            Log.info('scanDevice failed due to timeout.');
            this.showPopup = false
            if (this.deviceState == 1) {
                this.deviceState = 3
                bleOperator.stopBluetoothDevicesDiscovery();
                bleOperator.closeBleConnection(this.macAddr);
            }
        }, config.pairTimeout * 1000);
        bleOperator.startBluetoothDevicesDiscovery(config.bleScanFilterServices, this.macAddr, false, 30);
    },
    async isBleOpen() {
        let result = await bleOperator.getBluetoothAdapterState()
        Log.info('code = ' + result.code)
        Log.info('isAvailable = ' + result.data.isAvailable)
        if (result.code == 0) {
            let isOpen = result.data.isAvailable
            return isOpen
        } else {
            return false
        }
    },
    startConnectOnClick() {
        this.checkAndRequestPermissions();
    },
    async disconnectOnClick() {
        this.deviceState = 3
        this.tagId = ''
        bleOperator.closeBleConnection(this.macAddr);
    },
    async reConnectOnClick() {
        if (!await this.isBleOpen()) {
            bleOperator.openBluetoothAdapter()
            return
        }
        this.scanDevice()

    },
    /**
     * 协议校验 （从协议标识首节至协议内容尾字节求累加和后再对 256 取余）
     * @param changeData
     */
    verifyProtocol(changeData) {
        if (changeData.length < 14) return false;
        var checkHex = changeData.slice(0, -2);
        var lastHex = changeData.slice(-2);
        return this.sumComplementation(checkHex) == parseInt(lastHex, 16);
    },
    // 总合求余
    sumComplementation(data) {
        let sum = 0;
        for (let i = 0; i < data.length / 2; i++) {
            sum += parseInt(data.slice(i * 2, (i + 1) * 2), 16)
        }
        return parseInt(sum) % 256
    },
    goDetail() {
        if (this.tagId == "00070009") {
            router.push({
                uri: 'pages/detail/detail',
                params: {
                    title: this.deviceName,
                    tagId: this.tagId,
                    macAddr: this.macAddr,
                    reportValue1: this.reportValue1,
                    reportValue2: this.reportValue2,
                    reportValue3: this.reportValue3,
                    threshold1: this.threshold1,
                    threshold2: this.threshold2,
                    threshold3: this.threshold3,
                }
            });
        } else {
            router.push({
                uri: 'pages/issued/issued',
                params: {
                    title: this.deviceName,
                    tagId: this.tagId,
                    macAddr: this.macAddr,
                    threshold1: this.threshold1,
                    threshold2: this.threshold2,
                }
            });
        }
    },
    toMustSee() {
        commonOperator.startAbility(config.BUNDLE_NAME, config.WebAbility, callbackJson => {

        }, {
            url: config.seeUrl,
            title: "新人必看"
        }, {
            flags: 286435456
        });
    },
    toMustStudy() {
        commonOperator.startAbility(config.BUNDLE_NAME, config.WebAbility, callbackJson => {

        }, {
            url: config.studyUrl,
            title: "学习天堂"
        }, {
            flags: 286435456
        });
    },

    onDestroy() {
        Log.log(TAG + 'onDestroy');

    },
    backClick() {
        app.terminate();
    },
    onBackPress() {
        Log.log(TAG + 'onBackPress');
        if (this.showPopup) {
            //            this.showPopup = false
            return true
        }
        return false
    }
}
